<?php
namespace app\mp\admin;
use app\system\admin\Admin;
use think\Db;
use app\common\service\StallFeed as StallFeedService;
use app\common\service\Material as MaterialService;
use app\common\service\OrderMaterial as OrderMaterialService;
use app\common\service\Order as OrderService;
use app\common\service\OrderMaterialItem as OrderMaterialItemService;
use app\common\service\OrderMergeCut as OrderMergeCutService;
class StallFeed extends Admin
{
	/**
     * 采购对账
     *
     * @author 飞燕
     * @date 2021年3月16日
     *
     * @return Json
     */
    public function index()
    {
    	$status       = $this->request->param('status/s', 1);
    	$systemUserKV = getSystemUserKV(null);
		$stallsKV= getStallsKV();
		$where[] = ['sf.status', '<>', 0];

		if($status==3){ //复合对帐
			if ($this->request->isAjax()) {
				$where      = $data = [];
				$page       = $this->request->param('page/d', 1);
				$limit      = $this->request->param('limit/d', 20);
				$stallId    = $this->request->param('stall_id/d', 0);
				$billmonthDate    = $this->request->param('create_date_range/s');
                $paytype    = $this->request->param('pay_type/d', '');
                $max_moeny    = $this->request->param('max_money/d', '');
                $min_money    = $this->request->param('min_money/d', '');
                if ($min_money) {
                    $where[] = ['amount_money', '>=', $min_money];
                }
                if ($max_moeny) {
                    $where[] = ['amount_money', '<=', $max_moeny];
                }
				if ($stallId) {
					$where[] = ['stall_id', '=', $stallId];
				}
                if ($paytype) {
                    $where[] = ['pay_type', '=', $paytype];
                }
				if ($billmonthDate != '') {
					list($startTime, $endTime) =explode('~', $billmonthDate);// array_map('strtotime', explode('~', $billmonthDate));
					$where[] = ['pay_month', 'between', [substr($startTime,0,7), substr(trim($endTime),0,7)]];
				}
				$list = db('stall_bill')->where($where)->page($page)->order("create_time desc")->limit($limit)->select();
                foreach ($list as $key => $value) {
                    $list[$key]['mInfo']=["color"=>'',"colornum"=>'','material_sku'=>'','model'=>'','name'=>'','type'=>'','unit'=>"米"];
                    $list[$key]['oInfo']=['ordertime'=>''];
                    $list[$key]['sfInfo']=['client_ordernum'=>''];
                    $list[$key]['stall_name']= arrayGet($stallsKV, $value['stall_id'], '');
                    $list[$key]['recheck_create_user']= arrayGet($systemUserKV,$value['admin_id'], '');
                }
				$data['count'] = db('stall_bill')->where($where)->count();
				$data['data'] = $list;
				$data['code'] = 0;
				$data['msg'] = '';
				$data['status'] = $status;
				$statData1 = db('stall_feed sf')->join('order o', "sf.order_id=o.id", 'left')
                    ->where([['sf.create_time', '>=', strtotime('2022-01-01 00:00:00')]])->group('sf.status')->fieldRaw('sf.`status`,count(sf.status)')->select();
				$data['statData']=[];
				foreach ($statData1 as $key => $value) {
					$data['statData'][$value['status']]=$value['count(sf.status)'];
				}
				$data['statData'][3]=db('stall_bill')->where($where)->count();
				return json($data);
			}
		}
        $factoryKV = getFactoryKV(true);
    	if ($this->request->isAjax() || $this->request->param('export/d', 0)) {
    		$data =$wheres= [];
    		$page       = $this->request->param('page/d', 1);
    		$limit      = $this->request->param('limit/d', 20);
    		$clientOrdernum    = $this->request->param('client_ordernum/s', '');
			$stallOrder    = $this->request->param('stall_order/s', '');
			$stallId    = $this->request->param('stall_id/d', 0);
    		$sku    = $this->request->param('sku/s', '');
			$name    = $this->request->param('name/s', '');
    		$createDateRange    = $this->request->param('create_date_range/s');
			$startOrderTime    = $this->request->param('stall_order_time/s','');
            $factorId      = $this->request->param('factory_id/s', '');
            $checkuid      = $this->request->param('checkuser/s', '');
            $caigouUser      = $this->request->param('caigou_user/s', '');
            if ($checkuid != '') {
                $where[] = ['check_uid', 'in', db('system_user')->where('nick', 'like', "%{$checkuid}%")->column('id')];
            }
            if ($caigouUser != '') {
                $where[] = ['sf.caigou_user_id', 'in', db('system_user')->where('nick', 'like', "%{$caigouUser}%")->column('id')];
            }
			$export     = $this->request->param('export/d', 0);
			if ($export) {
				set_time_limit(0);
				ini_set('memory_limit', '1024M');
				$page = 1;
				$limit = 99999;
			}
			$where[] = ['sf.status', '=', $status];
            $where[] = ['sf.create_time', '>=', strtotime('2022-01-01 00:00:00')];
            if ($factorId) {
                $where[] = ['o.factory_id', '=', $factorId];
            }
    		if ($clientOrdernum != '') {
    			$where[] = ['sf.client_ordernum', '=', $clientOrdernum];
    		}
			if ($stallOrder != '') {
    			$where[] = ['sf.stall_order', '=', $stallOrder];
    		}
			if ($stallId) {
    			$where[] = ['sf.stall_id', '=', $stallId];
    		}
			if ($sku != '') {
    			$where[] = ['o.sku', '=', $sku];
    		}
			if ($name != '') {
				$materialIds=db('material')->where("name like '".$name."'")->column('id');
    			$where[] = ['material_id', 'in', $materialIds];
    		}
    		if ($createDateRange != '') {
    			list($startTime, $endTime) = array_map('strtotime', explode('~', $createDateRange));
    			$where[] = ['o.create_time', 'between', [$startTime, $endTime+86399]];
    		}
			if ($startOrderTime != '') {
    			list($startOrderTime, $endTime) = array_map('strtotime', explode('~', $startOrderTime));
    			$where[] = ['sf.stall_order_time', 'between', [$startOrderTime, $endTime+86399]];
    		}
			$orderMaterialService=new OrderMaterialService();
    		$materialService = new MaterialService();
            $orderMergeCutService = new OrderMergeCutService();
    		//1.合裁标签、-采料名称，11 2.订单数、3.实裁数、--分配工厂；11 4.开单采购总数（米）、--可加 5.条数明细、 可以加 6.实际单件用量、 可以加 7.余料情况、，订单该材料余料，可以加
            // 8.入库米数、 可以加 9.退换料状态 ---可处理； 换料-待处理； --- 10.实际总用量-- 可加； 11：单价差异-- 可加 111 12：总用量差异--
            //查询余料  stock_action表，   type=1 stock_m_type=2 and id=121010;  stock_m_type 0订单料1备料2余料
            //入库米数 stock_action表，   type=1 stock_m_type=2 and id=121010 and action_state=110;
            //退换状态，，material_return表 status 0,1,2 待审换退
            //caigou_unitprice customer_price 采购单价 mes单价 om表\
            $whereRaw = '1=1 ';
            $diff_metre= $this->request->param('diff_metre', '');
            $diff_metre_logic=$this->request->param('diff_count_logic', '');
            $price_diff= $this->request->param('price_diff', '');
            $price_diff_logic=$this->request->param('price_diff_logic', '');
            if($price_diff!==''){
                $logic=array('gt'=>'>','lt'=>'<','eq'=>'=');
                $whereRaw=' om.customer_price-sf.caigou_unitprice '.$logic[$price_diff_logic].$price_diff;
            }

    		$data['data'] = db('stall_feed sf')->join('order o', "sf.order_id=o.id", 'left')
                ->field('sf.*,sf.client_ordernum as another_client_ordernum,o.sku,o.client_status,sf.stall_order_time,o.create_time as order_time,o.quantity,o.client_ordernum,o.factory_id,
                om.tiaoshu_detail,om.mid, om.order_id,caichuang_shiji_dosage,billing_caigou_count,tiaoshu,is_share,customer_price,om.shicai_count')
                ->join('order_material om', 'om.mid =sf.order_material_id','left')
                ->whereRaw($whereRaw)
                ->where($where)->order("sf.create_time desc,check_time desc")->page($page)->limit($limit)->select();
    		//查询余料情况 及入库情况
    		$inStockRet=db("stock_action")
                ->field("order_id,client_ordernum,material_id,sum(use_num) as surplus_total,
                sum(CASE  WHEN action_state=110  THEN use_num ELSE 0 END) as in_stocktotal")
                ->where("type=1 and stock_m_type=2")->where([ ['order_id', 'in', array_column($data['data'],'order_id')]])
                ->group("order_id,material_id")->select();
    		$haveStocks=[];
    		foreach ($inStockRet as $key=>$stockinfo){
                $haveStocks[$stockinfo['order_id']][$stockinfo['material_id']]=$stockinfo;
            }
            //$data['lastsql']=lastsql();
    		foreach ($data['data'] as $k => &$v) {
				$omInfo=$orderMaterialService->getInfoById($v['order_material_id'], 'tiaoshu,is_share,customer_price');
                $omcInfo=$orderMergeCutService->getInfoByClientOrdernum($v['client_ordernum'], 'id,client_ordernum');
                if($omcInfo) {
                    $data['data'][$k]['omc_status']=1;
                    $data['data'][$k]['omc_client_ordernums']=$omcInfo['client_ordernum'];
                }
                $v['dosage_count']=round($v['caichuang_shiji_dosage']*$v['shicai_count'],2); //总用量
                $v['dosage_use_diff']=empty($v['shicai_count']) ? 0 : round($v['dosage_count']-$v['billing_caigou_count'],2); //|| empty($v['caichuang_shiji_dosage']) 总用量差异
                $v['price_diff']=round($v['customer_price']-$v['caigou_unitprice'],2); //单价差异
                $v['surplus_metre']=isset($haveStocks[$v['order_id']][$v['material_id']]) ? $haveStocks[$v['order_id']][$v['material_id']]['surplus_total'] : 0;
                $v['in_stocktotal']=isset($haveStocks[$v['order_id']][$v['material_id']]) ? $haveStocks[$v['order_id']][$v['material_id']]['in_stocktotal'] : 0;
				$data['data'][$k]['tiaoshu']=$omInfo?$omInfo['tiaoshu']:0;
				$data['data'][$k]['is_share']=$omInfo?$omInfo['is_share']:0;
				$v['win_money']=isset($omInfo['win_money'])? $omInfo['win_money'] :0;
                $v['client_ordernum']=empty($v['client_ordernum'])? $v['another_client_ordernum'] :$v['client_ordernum'];
                $data['data'][$k]['oInfo']=['ordertime'=>''];
                $data['data'][$k]['sfInfo']=['client_ordernum'=>''];
                $v['settle_unitprice']=substr($v['settle_unitprice'],-1)=='0' ? substr($v['settle_unitprice'],0,strlen($v['settle_unitprice'])-1) :$v['settle_unitprice'];
                $v['caigou_unitprice']=substr($v['caigou_unitprice'],-1)=='0' ? substr($v['caigou_unitprice'],0,strlen($v['caigou_unitprice'])-1) :$v['caigou_unitprice'];
                $data['data'][$k]['amount']=round(floatval($v['billing_caigou_count_feed'])*floatval($v['caigou_unitprice']),2);
    			$data['data'][$k]['mInfo'] = $materialService->getInfoById($v['material_id'], 'name,color,type,material_sku,model,colornum,unit,customer_price');
    			if(empty($data['data'][$k]['mInfo'])){
                    $data['data'][$k]['mInfo']=["color"=>'',"colornum"=>'','material_sku'=>'','model'=>'','name'=>$v['material_name'],'type'=>'','unit'=>"",'customer_price'=>''];
                }
                $v['customer_price']=isset($omInfo['customer_price']) ? $omInfo['customer_price'] :  0;
				$data['data'][$k]['billing_caigou_amount'] = $v['billing_caigou_amount']==0?round($v['caigou_unitprice']*$v['billing_caigou_count_feed'],2):$v['billing_caigou_amount'];
                $data['data'][$k]['admin_name']= arrayGet($systemUserKV,$v['admin_id'], '');
                $data['data'][$k]['caigou_name']= arrayGet($systemUserKV,$v['caigou_user_id'], '');
                $data['data'][$k]['check_name']= arrayGet($systemUserKV,$v['check_uid'], '');
				$data['data'][$k]['stall_name']= arrayGet($stallsKV, $v['stall_id'], '');
                $data['data'][$k]['total_amount']=round(floatval($data['data'][$k]['amount']));
    		}
    		$data['count'] = db('stall_feed sf')->join('order o', "sf.order_id=o.id", 'left')->field('sf.*,o.sku,o.create_time as order_time,o.quantity,o.client_ordernum')->where($where)->count('sf.id');
			$stallFeedIds= array_column($data['data'], 'id','');
    		$data['code'] = 0;
    		$data['msg'] = '';
			$data['status'] = $status;
			foreach ($where as $kw => $vw) {
				if($vw[0]=='sf.status' && $vw[1]=='=')	 continue;
				$wheres[]=$vw;
			}
			$statData1 = db('stall_feed sf')->join('order o', "sf.order_id=o.id", 'left')->group('sf.status')->where($wheres)->fieldRaw('sf.`status`,count(sf.status)')->select();
			$data['statData']=[];
			foreach ($statData1 as $key => $value) {
				$data['statData'][$value['status']]=$value['count(sf.status)'];
			}
			$bill_where=empty($stallId)?[]:['stall_id'=>$stallId];
			$data['statData'][3]=db('stall_bill')->where($bill_where)->count();
			if ($export) {
    			$this->_exportXls('采购对账-' .date('YmdHis'), $data['data']);
    			exit;
    		}
    		return json($data);
    	}

    	// 条数统计
		$statData1 = db('stall_feed sf')->join('order o', "sf.order_id=o.id", 'left')->group('sf.status')->where($where)->fieldRaw('sf.`status`,count(sf.status)')->select();	//dump($statData1);
		$statData=[];
		foreach ($statData1 as $key => $value) {
			$statData[$value['status']]=$value['count(sf.status)'];
		}
		$statData[3]=db('stall_bill')->count();
		$billmonth=[];
		for($index=-1;$index<6;$index++){
		    $monthval=-$index;
            $billmonth[date('Y-m',strtotime("$monthval month"))]=date('Y-m',strtotime("$monthval month"));
        }
        $caigouUsers=['0' => '请选择']+db("system_user suser")->join('system_user_role srole', "suser.id=srole.user_id", 'left')
                ->where("srole.role_id=5")->column("suser.nick","id");
    	$assign = [
    	    'billmonth'=>$billmonth,'select_month'=>date("Y-m",strtotime("-1 month")),
            'caigouUserKV'=>$caigouUsers,
    		'status' => $status,
            'factoryKV' => [0 => '请选择'] + $factoryKV,
			'statData'=>$statData,
			'stallsKV' => ['' => '请选择'] + $stallsKV,
    		'clientStatus' => config('mimo.client_status'),
    	];
    	return $this->assign($assign)->fetch();
    }

    //采购入单确认功能
    public function stallFeedConfirm() {
        $id  = $this->request->param('id/d', 0);
        $stallFeedType   = $this->request->param('stall_feed_type/s','');
        $stallId   = $this->request->param('stall_id/d', 0);
        $caigouUnitprice   = $this->request->param('caigou_unitprice/f', 0);
        $client_ordernum   = $this->request->param('client_ordernum/s', '');
        $material_name   = $this->request->param('material_name/s', '');
        $stallOrderTime   = $this->request->param('stall_order_time/s', '');
        $stallOrder   = $this->request->param('stall_order/s', '');
        $billingCaigouCountFeed   = $this->request->param('billing_caigou_count_feed/s', '');
        $action_event=$this->request->param('action_event/s', '');
        if($action_event=='delete'){
            $stallFeedService= new StallFeedService();
            // 记录原始开单采购数
            $sfInfo = $stallFeedService->getInfoById($id);
            if (empty($sfInfo)){
                throw new \Exception('数据异常');
            }
            db()->startTrans();
            //删除入单信息
            db('stall_feed')->where('id', $id)->delete();
            //$this->addOrderLog($sfInfo['order_id'], $sfInfo['client_ordernum'], "物料[".getMaterialName($sfInfo['material_id'])."]入单操作 删除一个入单信息");
            db()->commit();
            $result = [
                'order_id' =>  $sfInfo['order_id'],
            ];
            return $this->Json(1,'',$result);die;
        }
        if($stallId==0) return $this->error('请选择供应商');
        try {
            db()->startTrans();
            $orderMaterialService = new OrderMaterialService();
            $stallFeedService= new StallFeedService();
            // 记录原始开单采购数
            $sfInfo = $stallFeedService->getInfoById($id);
            if (empty($sfInfo)){
                throw new \Exception('数据异常');
            }
            if ($billingCaigouCountFeed == '' || floatval($billingCaigouCountFeed) == 0) {
                throw new \Exception(',采购入单填写错误,米数数据不能为零');
            }
            $orderId = $sfInfo['order_id'];
            $billingCaigouCountFeed = floatval($billingCaigouCountFeed);
            $omInfo=$orderMaterialService->getInfoById($sfInfo['order_material_id'], "customer_price,billing_caigou_count,caigou_unitprice,mid,caigou_subtotal_money,billing_caigou_count_ori");

            $oud = [
                'update_time' => time(),
                'status' => 1,
                'stall_feed_type'=>$stallFeedType,
                'billing_caigou_count_feed'=> $billingCaigouCountFeed,
                'caigou_unitprice' => $caigouUnitprice,
                'client_ordernum' => $client_ordernum,
                'caigou_user_id'=>$this->request->param('caigou_user_id/d', 0),
                'material_name'=>$material_name,
                'stall_id' => $stallId,
                'stall_order'=>$stallOrder,
                'stall_order_time'=>strtotime($stallOrderTime)?strtotime($stallOrderTime):0,
                'settle_unitprice'=> $caigouUnitprice,
            ];
            $oud['settle_amount'] = round($oud['caigou_unitprice'] * abs(floatval($billingCaigouCountFeed)), 2);
            $res = db('stall_feed')->where('id', $id)->update($oud);

            db()->commit();
            $result = [
                'order_id' => $orderId,
                'caigou_unitprice'=>$caigouUnitprice,
                'billing_caigou_kgprice'=>0
            ];
            return $this->Json(1,'',$result);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

    /**
     * 退补明细审核
     * @author 飞燕
     * @date 2021年3月16日
     * @throws \Exception
     */
    public function status()
    {
    	$val        = $this->request->param('val/d', 0);
    	$ids         = $this->request->param('id', []);
    	if (empty($ids)) {
    		return $this->error('缺少id参数');
    	}

    	try {
    		db()->startTrans();
			$stallFeedService= new StallFeedService();
			foreach ($ids as $key => $id) {

				$sfInfo = $stallFeedService->getInfoById($id);
				if (empty($sfInfo)) {
					return $this->error('未找到相关记录');
				}
				$orderId = $sfInfo['order_id'];
				$upData = [
					'status' => $val,
                    'check_uid'=>ADMIN_ID,
					'update_time' => time(),
					'check_time' => time(),
				];
				$materialName = getMaterialName($sfInfo['material_id']);

				db('stall_feed')->where('id', $id)->update($upData);
				$this->addOrderLog($orderId, $sfInfo['client_ordernum'], "物料[{$materialName}]退补明细审核");
			}
    		db()->commit();
    		return $this->Json(1);
    	} catch (\Exception $e) {
    		db()->rollback();
    		return $this->Json(0, '操作失败，'. $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
    	}
    }

	/**
     * 编辑采购总金额
     *
     * @author 飞燕
     * @date 2021年3月16日
     *
     * @throws \Exception
     */
	public function stallFeedEdit(){
		$id       = $this->request->param('id/d', 0);
		$stallId       = $this->request->param('stall_id/d', 0);
    	$billingCaigouAmount   = $this->request->param('billing_caigou_amount/f', 0);

		$stallFeedService=new StallFeedService();
		$sfInfo = $stallFeedService->getInfoById($id);
		if(!$sfInfo) return $this->error("数据异常");
		if($billingCaigouAmount) $upData['billing_caigou_amount'] = $billingCaigouAmount;
		if($stallId) $upData['stall_id'] = $stallId;
		$upData['update_time'] = time();
    	$ret = db('stall_feed')->where('id', $id)->update($upData);

    	$this->addOrderLog($sfInfo['order_id'], $sfInfo['client_ordernum'], "采购对帐修改物料[".getMaterialName($sfInfo['material_id'])."]采购总金额为{$billingCaigouAmount}");
    	if ($ret) {
    		return $this->Json(1, '保存信息成功');
    	} else return $this->Json(0);
	}

    /**
     * 调整结算单价
     * @author sparkguo 08-03
     */
	public function changeSettleUnitprice(){
        $id       = $this->request->param('id/d', 0);
        $settleUnitprice   = $this->request->param('settle_unitprice/f', 0);

        $stallFeedService=new StallFeedService();
        $sfInfo = $stallFeedService->getInfoById($id);

        if(!$sfInfo) return $this->error("数据异常");
        $upData['settle_unitprice'] = $settleUnitprice;
        $upData['settle_amount'] = round($sfInfo['billing_caigou_count_feed']*$settleUnitprice,2);
        $ret = db('stall_feed')->where('id', $id)->update($upData);
        $this->addOrderLog($sfInfo['order_id'], $sfInfo['client_ordernum'], "采购对帐调整物料[".getMaterialName($sfInfo['material_id'])."]采购结算单价为{$settleUnitprice}");
        if ($ret) {
            return $this->Json(1, '信息修改成功',$upData);
        } else return $this->Json(0);
    }

    /**
     * 增加采购入单 新增入单列表
     * @author  sparkguo   20220428
     */
    public function addStallFeed(){
        $mid  = $this->request->param('mid/d', 7022);
        $action=$this->request->param('action', 'showlist');
        if($action=="costFeedAdd"){
            $result=$this->costFeed();
            return $result;
        }elseif($action=="stallFeedConfirm"){
            $result = $this->stallFeedConfirm();
            return $result;
        }
        $stallsKV = getStallsKV();
        $orderMaterialService = new OrderMaterialService();
        $omInfo=$orderMaterialService->getInfoById($mid, "client_ordernum,material_id,fabric_width,weight,customer_price");
        //if(!$omInfo) return $this->error("数据异常");
        if ($this->request->isAjax() || $this->request->param('export/d', 0)) {

            $materialService = new MaterialService();
            //$orderMaterialItemService = new OrderMaterialItemService();
            $clientOrdernum  = $this->request->param('client_ordernum/s');
            $stallId    = $this->request->param('stall_id/d', 0);
            $stallOrder    = $this->request->param('stall_order/s', '');
            $materialName    = $this->request->param('material_name/s', '');

            $page       = $this->request->param('page/d', 1);
            $limit      = $this->request->param('limit/d', 20);
            $export     = $this->request->param('export/d', 0);
            $where      = $data = [];

            $where[] = ['order_material_id', '=', 0];
            $where[] = ['original', '=', 0];
            if ($clientOrdernum != '') {
                $where[] = ['client_ordernum', '=', $clientOrdernum];
            }
            if ($stallOrder != '') {
                $where[] = ['stall_order', '=', $stallOrder];
            }
            if ($stallId) {
                $where[] = ['stall_id', '=', $stallId];
            }
            if ($materialName != '') {
                $where[] = ['material_name', 'like',  "%".$materialName."%"];
            }

            $order="id desc";
            $data['data'] = db('stall_feed')->where($where)->page($page)->limit($limit)->order($order)->select();

            $data['mInfo']=$materialService->getInfoById($omInfo['material_id'],'supplier');
            $data['mInfo']['weight'] = $omInfo['weight'];
            $data['mInfo']['fabric_width'] = $omInfo['fabric_width'];
            $sellerNameKeyDatas=array_flip($stallsKV);
            $sellerOtherNames=[];
            $seller=db('stalls')->where([['othernames','<>','']])->order("id asc")->column('othernames', 'id');
            foreach ($seller as $id=>$othername){
                $othernameArr=explode('，',trim($othername,'，'));
                foreach ($othernameArr as $othernameStr){
                    $sellerOtherNames[$othernameStr]=$id;
                }
            }
            foreach ($data['data'] as $key => &$value) {
                $value['stall_id']=$value['stall_id']==0 ? '' : $value['stall_id'] ;
                $data['data'][$key]['caigou_amount']=sprintf("%.2f",$value['billing_caigou_count_feed']*$value['caigou_unitprice']);
                $data['data'][$key]['customer_price']=$omInfo['customer_price'];
                $value['caigou_unitprice']=substr($value['caigou_unitprice'],-1)=='0' ? substr($value['caigou_unitprice'],0,strlen($value['caigou_unitprice'])-1) :$value['caigou_unitprice'];
                $data['data'][$key]['stall_id']=$data['data'][$key]['stall_id']==0 ? (isset($sellerNameKeyDatas[$data['mInfo']['supplier']]) ? $sellerNameKeyDatas[$data['mInfo']['supplier']] : 0 ) : $data['data'][$key]['stall_id'];//匹配档口名称
                //供应商为空则尝试匹配其它关联档口名称
                $data['data'][$key]['stall_id']=$data['data'][$key]['stall_id']==0 ? (isset($sellerOtherNames[$data['mInfo']['supplier']]) ? $sellerOtherNames[$data['mInfo']['supplier']] : 0 ) : $data['data'][$key]['stall_id'];
                $data['data'][$key]['mInfo'] = $data['mInfo'];
            }
            $data['count'] = db('stall_feed')->where($where)->count('id');
            $data['code'] = 0;
            $data['msg'] = '';
            return json($data);
        }
        $caigouUsers=['0' => '请选择']+db("system_user suser")->join('system_user_role srole', "suser.id=srole.user_id", 'left')
                ->where("srole.role_id=5")->column("suser.nick","id");
        $assign = [
            'mid' => $mid,
            'caigouUserKV'=>$caigouUsers,
            'stallsKV' => ['' => '请选择'] + $stallsKV,
        ];
        return $this->assign($assign)->fetch();
    }
    /**
     * 采购入单 增加入单
     * @author sparkguo
     * @date 2020年7月31日
     */
    private function costFeed() {
        $mid  = $this->request->param('mid/d', 0);
        $number = $this->request->post('number/f', 0); //  采购单价
        $billingCaigouKgcount=$this->request->post('billing_caigou_kgcount/f', 0); // 开单公斤数-- 采购数量
        $orderService = new OrderService();
        $orderMaterialService = new OrderMaterialService();
        $orderMaterialItemService=new OrderMaterialItemService();
        $stallFeedService=new StallFeedService();
        try {
            db()->startTrans();

            $omInfo = ['order_id'=>0,'billing_caigou_count'=>0,'client_ordernum'=>'','material_id'=>0,'mid'=>0,'order_id'=>0,'caigou_unitprice'=>0,'billing_caigou_count_ori'=>0];
            if (empty($omInfo)){
                throw new \Exception('数据异常');
            }

            $orderId = $omInfo['order_id'];

            $billingCaigouCount = $omInfo['billing_caigou_count'] + $number;
            //新增补退明细表记录
            $omiList=$orderMaterialItemService->getListByOrderMaterialId($mid,"stalls_id");
            if($omiList) $sfData['stall_id']=$omiList[0]['stalls_id'];
            $sfData=[
                'billing_caigou_count_feed'=>$billingCaigouKgcount,
                'caigou_unitprice' => $number,
                'billing_caigou_kgcount' => 0,//
                'order_material_id'=>$mid,
                'caigou_user_id'=>$this->request->param('caigou_user_id/d', 0),
                'order_id'=>$omInfo['order_id'],
                'client_ordernum'=>$omInfo['client_ordernum'],
                'material_id'=>$omInfo['material_id'],
                'admin_id'=>ADMIN_ID,
                'update_time' => time(),
                'create_time' => time(),
            ];
            db('stall_feed')->insert($sfData);
            //同时更新order_material和order
            $sfList=$stallFeedService->getListByMid($omInfo['mid']);
            $caigouSubtotalMoney = $omInfo['caigou_unitprice'] * $omInfo['billing_caigou_count_ori'];
            foreach ($sfList as $key => $value) {
                $caigouSubtotalMoney = $caigouSubtotalMoney+($value['caigou_unitprice']*$value['billing_caigou_count_feed']);
            }

            db()->commit();
            $res = [
                'order_id' => $orderId,
                'billing_caigou_count' => $billingCaigouCount,
                'caigou_subtotal_money' => $caigouSubtotalMoney,
                'caigou_total_money' => $caigouSubtotalMoney
            ];
            return $this->Json(1, '', $res);
        } catch (\Exception $e) {
            db()->rollback();
            return $this->Json(0, '操作失败，' . $e->getMessage(), ['line' => $e->getLine(), 'file' => $e->getFile()]);
        }
    }

	/**
	 * 导出
	 *
	 */
	private function _exportXls($title, &$list) {
		$params = [];
		$data = [];
        $factoryKV =[0=>'']+getFactoryKV(true);
        $pay_type=[''=>'',1=>'月结',2=>'现金'];
        $material_type=[''=>'','fabric'=>'面料','lining'=>'里料','accessories'=>'辅料'];
		foreach ($list as $k => $v) {
			$data[] =
                [
                date('Y-m-d H:i:s', $v['create_time'])?date('Y-m-d H:i:s', $v['create_time']):'',
                $v['client_ordernum'],
                $v['sku'],
                $v['stall_name'],
                $v['mInfo']['name'],
                $v['mInfo']['color'],
                //$v['oInfo']['caigou_over_time']!=0?date('Y-m-d H:i:s', $v['oInfo']['caigou_over_time']):'',
                $v['stall_order_time']==0 ? '':date('Y-m-d', $v['stall_order_time']),
                $v['stall_order'],
                $v['billing_caigou_count_feed'],
                $v['caigou_unitprice'],
                $v['customer_price'],
                $v['tiaoshu'],
                $v['mInfo']['unit'],
                $v['billing_caigou_kgprice'],
                $v['billing_caigou_kgcount'],
                $v['settle_unitprice'],
                $v['settle_amount'],
                $v['amount'],
                $v['total_amount'],
                isset($v['stall_cost_type'])?$v['stall_cost_type']:'',
                isset($v['stall_cost_money'])?$v['stall_cost_money']:'',
                '',
                $material_type[$v['mInfo']['type']],
                '',
                isset($v['factory_id'])? $factoryKV[$v['factory_id']] :'',
                isset($v['client_status']) ? ( $v['client_status']==99 ? '已废除': '未废除') : '未废除',
                isset($v['win_money'])? $v['win_money'] :0.00,
            ];
		}

		$params['file'] = $title;
		$params['sheet'] = [
			[
				//'head' => ['审核时间','下单时间','订单号','sku','材料名称','颜色','供应商','供应商单单号','供应商单日期','采购单价','MES单价','采购条数','采购数量','开单采购公斤数','开单采购公斤价','结算单价','结算金额','采购总金额','经手人'], // 表头
                'head' => ['下单日期','订单号','物料sku','供应商','材料名称','颜色','供应商单日期','供应商单单号','采购数量','采购单价','MES单价','采购条数','单位','采购公斤价','采购公斤数',
                    '结算单价','结算金额','采购总金额','总计','费用单类型','费用单金额（元）','结款方式','材料类型','归属月份','工厂分配','是否废除','盈亏情况'], // 表头
				'data' => $data,
			],
		];
		unset($list);
		plugins_run('excel/excel/export', $params);
	}
}

